﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace PayloadTracker.Tiles
{
    [Serializable]
    public class ProviderConfiguration
    {
        List<ITileProvider> m_TileProviders;
        [XmlArray("Providers")]
        [XmlArrayItem("Provider", Type = typeof(Utility.Xml.AbstractXmlSerializer<ITileProvider>))]
        public List<ITileProvider> TileProviders
        {
            get { return m_TileProviders; }
            set { m_TileProviders = value; }
        }

        public ProviderConfiguration()
        {
            m_TileProviders = new List<ITileProvider>();
        }
        /// <summary>
        /// Save to file
        /// </summary>
        /// <param name="Filename"></param>
        public void Save(string Filename)
        {
            var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(ProviderConfiguration));
            var writerSettings = new System.Xml.XmlWriterSettings();
            writerSettings.Indent = true;
            writerSettings.OmitXmlDeclaration = true;
            var writer = System.Xml.XmlWriter.Create(Filename, writerSettings);
            xmlSerializer.Serialize(writer, this);

            writer.Flush();
            writer.Close();
        }
        /// <summary>
        /// Load from file
        /// </summary>
        /// <param name="Filename"></param>
        public static ProviderConfiguration Load(string Filename)
        {
            if (!System.IO.File.Exists(Filename))
            {
                Logger.LOG.WriteLine("Tile ProviderConfiguration does not exist creating new.");
                return new ProviderConfiguration();
            }
            try
            {
                XmlReaderSettings xrs = new XmlReaderSettings();
                xrs.CloseInput = true;
                var xmlDeserializer = new System.Xml.Serialization.XmlSerializer(typeof(ProviderConfiguration));
                using (var reader = System.Xml.XmlReader.Create(System.IO.File.OpenRead(Filename), xrs))
                    return xmlDeserializer.Deserialize(reader) as ProviderConfiguration;
            }
            catch (System.Exception ex)
            {
                Logger.LOG.Error("Loading ProviderConfiguration data from: " + Filename + ". Due to " + ex.Message + " Creating new.");

                return new ProviderConfiguration();
            }
        }

    }
}
